<template>
  <div :class="preview?'':'normal'">
    <Toolbar
        v-if="!preview"
        :defaultConfig="toolbarConfig"
        :editor="editorRef"
        :mode="mode"
        style="border-bottom: 1px solid #ccc;"
    />
    <Editor
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        :style="{overflowY: 'scroll',height: props.height}"
        @onCreated="handleCreated"
    />
  </div>
</template>
<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import {onBeforeUnmount, ref, shallowRef} from "vue";
import {Editor, Toolbar} from "@wangeditor/editor-for-vue";

const props = defineProps({
  preview: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: 'calc(100vh - 310px)'
  }
})
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
let mode = ref("default");
// 内容 HTML
let valueHtml = defineModel('content')
let urlPrev = import.meta.env.VITE_APP_PROXY_TARGET
const toolbarConfig = {};
const editorConfig = {
  readOnly: props.preview,
  placeholder: props.preview ? '' : '请输入内容',
  MENU_CONF: {},
};
if (!props.preview) {
  editorConfig.MENU_CONF.uploadImage = {
    server: `${urlPrev}/blog/uploadBlogContentImg/`,
    customInsert(res, insertFn) {
      const url = `${urlPrev}${res.url}`;
      insertFn(url, '博客图片', url);
    },
  };
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！

};
</script>
<style>
.normal {
  border: 1px solid #ccc;
}
</style>